package com.ctg.behavior.calc.controller.ltv;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import com.ctg.behavior.common.ltv.CtLTVCalcRequest;
import com.ctg.behavior.common.ltv.CtLTVCalcResult;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.common.CtgResult;
import com.ctg.behavior.common.ltv.CtLTVCalcBody;
import com.ctg.behavior.common.ltv.CtLTVCalcData;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/ltv")
public class LTVController {

    @Value("${simulator.path}")
    private String simlutorPath;

    @PostMapping("/report")
    public CtLTVCalcResult report(@RequestBody CtLTVCalcRequest body) throws Exception {
        CtLTVCalcResult result = new CtLTVCalcResult();

        String filePath = simlutorPath + "/ltv/report/";
        FileUtils.forceMkdir(new File(filePath));

//        String targetFilePath = this.builderTargetFilePath(filePath, body);

        // 检查文件并读取文件
//		File targetFile = new File(targetFilePath);
//		if (!targetFile.exists()) {
//			String resourceFile = "ltv/report/ltv.trend.json";
//			if ("contrast".equals(body.getChartType())) {
//				resourceFile = "ltv/report/ltv.contrast.json";
//			}
//			log.info("resourceFile :"+resourceFile);
//			ClassPathResource classPathResource = new ClassPathResource(resourceFile);
//			InputStream inputStream = classPathResource.getInputStream();
//			List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
//			StringBuilder sbuilder = new StringBuilder();
//			for (String line : lines) {
//				sbuilder.append(line);
//			}
//			result = JSON.parseObject(sbuilder.toString(), CtLTVCalcResult.class);
//		} else {
//			log.info("targetFile :"+targetFile.getAbsolutePath());
//			String resultText = FileUtils.readFileToString(targetFile, "UTF-8");
//			result = JSON.parseObject(resultText.toString(), CtLTVCalcResult.class);
//		}
//		log.info(result.toString());
        String resourceFile = "";
        if (body.getReq().getByFields().size() == 0) {
            resourceFile = "ltv/report/ltv.trend_all.json";
            if ("contrast".equals(body.getReq().getChartType())) {
                if (body.getReq().getMeasures().size() == 1) {
                    if (body.getReq().getMeasures().get(0).getField()==null) {
                        resourceFile = "ltv/report/ltv.contrast_filter_one.json";
                    }else{
                        resourceFile = "ltv/report/ltv.contrast_groupby_properties.json";
                    }
                }else{
                    resourceFile = "ltv/report/ltv.contrast_all.json";
                }
            }
        }else{
            resourceFile = "ltv/report/ltv.trend.json";
            if ("contrast".equals(body.getReq().getChartType())) {
                resourceFile = "ltv/report/ltv.contrast.json";
            }
        }
        log.info("resourceFile :" + resourceFile);
        ClassPathResource classPathResource = new ClassPathResource(resourceFile);
        InputStream inputStream = classPathResource.getInputStream();
        List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
        StringBuilder sbuilder = new StringBuilder();
        for (String line : lines) {
            sbuilder.append(line);
        }
        result = JSON.parseObject(sbuilder.toString(), CtLTVCalcResult.class);
        return result;
    }

    @PostMapping("/reportTMU")
    public CtgResult report(@RequestBody LTVTMUInfo body) throws Exception {
        CtgResult result = new CtgResult();

        String filePath = simlutorPath + "/ltv/report";
        FileUtils.forceMkdir(new File(filePath));

        String targetFilePath = this.builderTargetFilePath(filePath, body.getRequest());

        File targetFile = new File(targetFilePath);

        FileUtils.writeStringToFile(targetFile, JSON.toJSONString(body.getResponse()), "UTF-8");

        //result.setMsg("report response body updload successfully!(test mode)");

        return result;
    }

    public String builderTargetFilePath(String filePath, CtLTVCalcBody body) {

        // 拼JSON文件名
        String targetFilePath = filePath;
        // 1. 初始事件/初始时间(用户属性)
        if (StringUtils.isEmpty(body.getStartSign().getStartTimeField())) {
            targetFilePath += "/startEvent_";
        } else {
            targetFilePath += "/startTimeField_";
        }
        // 2. 趋势：trend / 对比：contrast
        String chartType = body.getChartType();
        if ("contrast".equals(chartType)) {
            targetFilePath += chartType;
            targetFilePath += "_";
            // 3. LTV级别：0/1/2/3/....
            targetFilePath += body.getChartIndex();
        } else {
            targetFilePath += "trend";
        }
        // 4. 是否“事件次数”：true/false
        if (!body.getMeasures().isEmpty() && !StringUtils.isEmpty(body.getMeasures().get(0).getField())) {
            targetFilePath += "_eventCount";
        } else {
            targetFilePath += "_NoEventCount";
        }
        // 5. 是滞“总体”分组：true/false
        if (body.getByFields().isEmpty()) {
            targetFilePath += "_All";
        } else {
            targetFilePath += "_NoAll";
        }
        targetFilePath += ".json";

        return targetFilePath;
    }

}
